package com.yami.shop.delivery.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.model.Delivery;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.delivery.common.model.DeliveryOrder;
import com.yami.shop.delivery.common.model.OrderSelfStation;
import com.yami.shop.delivery.common.param.DeliveryOrderItemParam;
import com.yami.shop.delivery.common.param.DvyOrderParam;
import com.yami.shop.delivery.common.param.ExchangeRightsParam;
import com.yami.shop.delivery.common.param.OrderParam;
import com.yami.shop.delivery.common.service.DeliveryOrderService;
import com.yami.shop.delivery.common.service.OrderSelfStationService;
import com.yami.shop.rights.common.dto.ExchangeRightsDto;
import com.yami.shop.rights.common.model.ExchangeRecord;
import com.yami.shop.rights.common.service.ExchangeRecordService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.DeliveryService;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserAddrOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.yami.shop.common.util.BeanUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lhd on 2020/05/15.
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/order/delivery")
@Tag(name = "商家端物流接口")
public class OrderDeliveryController {

    private final OrderItemService orderItemService;

    private final UserAddrOrderService userAddrOrderService;

    private final OrderService orderService;

    private final DeliveryOrderService deliveryOrderService;

    private final OrderSelfStationService orderSelfStationService;

    private final ExchangeRecordService exchangeRecordService;
    private final DeliveryService deliveryService;
    /**
     * 订单项待发货数量查询
     */
    @GetMapping("/getOrderItemUnDelivery/{orderNumber}")
    @Operation(summary =  "订单项待发货数量查询")
    @Parameter(name = "orderNumber", description = "订单号")
    public ServerResponseEntity<Order> getOrderItemUnDelivery(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber, shopId, true);
        if (Objects.isNull(order)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
        if (CollectionUtils.isEmpty(orderItems)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        Map<Long, Integer> orderItemMap = null;
        if (Objects.nonNull(order.getRefundStatus())) {
            orderItemMap = orderService.getOrderItemMap(order.getOrderId());
        }
        //查询已发货数量
        for (OrderItem orderItem : orderItems) {
            //根据状态查询可发货数量
            orderItem.setChangeNum(orderItem.getStatus() == -1 ? orderItem.getProdCount() : orderItem.getStatus());
            orderItem.setProdCount(orderItem.getChangeNum());
            if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(orderItem.getOrderItemId()))) {
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getOrderItemId()));
            } else if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(0L))) {
                orderItem.setReturnMoneySts(orderItemMap.get(0L));
            }
            // 退款修改赠品状态
            if(Objects.nonNull(orderItemMap) && Objects.nonNull(orderItem.getGiveawayOrderItemId()) && orderItemMap.containsKey(orderItem.getGiveawayOrderItemId())){
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getGiveawayOrderItemId()));
            }
        }
        order.setOrderItems(orderItems);
        return ServerResponseEntity.success(order);
    }



    @PutMapping("/orderItemsDelivery")
    @Operation(summary =  "订单项分包裹发货")
    @PreAuthorize("@pms.hasPermission('order:delivery:orderItemsDelivery')")
    public ServerResponseEntity<Void> orderItemsDelivery(@RequestBody DeliveryOrderItemParam deliveryOrderParam) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        deliveryOrderService.saveDeliveriesInfo(deliveryOrderParam, shopId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/getOrderDeliveries/{orderNumber}")
    @Operation(summary =  "根据订单号查询订单物流包裹信息")
    @Parameter(name = "orderNumber", description = "订单号")
    public ServerResponseEntity<List<DeliveryOrder>> getOrderDeliveries(@PathVariable("orderNumber") String orderNumber) {
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.listDetailDelivery(orderNumber);
        return ServerResponseEntity.success(deliveryOrders);
    }

    @PutMapping("/updateOrderDeliveries")
    @Operation(summary =  "修改订单物流包裹信息,也可修改兑换订单")
    @PreAuthorize("@pms.hasPermission('order:delivery:update')")
    public ServerResponseEntity<Void> updateOrderDeliveries(@RequestBody DvyOrderParam dvyOrderParam) {
        List<DeliveryOrder> deliveryOrders = dvyOrderParam.getDeliveryOrders();
        deliveryOrderService.updateOrderDeliveries(deliveryOrders);
        deliveryOrders.forEach(s->{
            if("1".equals(s.getOrderNumberType())){
                LambdaUpdateWrapper<ExchangeRecord> exchangeRecord1LambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                exchangeRecord1LambdaUpdateWrapper.eq(ExchangeRecord::getOrderNumber,s.getOrderNumber());
                exchangeRecord1LambdaUpdateWrapper.set(ExchangeRecord::getProvince,s.getProvince());
                exchangeRecord1LambdaUpdateWrapper.set(ExchangeRecord::getCity,s.getCity());
                exchangeRecordService.update(exchangeRecord1LambdaUpdateWrapper);
            }
        });
        return ServerResponseEntity.success();
    }


    @GetMapping("/orderInfo/{orderNumber}")
    @PreAuthorize("@pms.hasPermission('order:get:info')")
    @Operation(summary =  "根据订单号获取订单物流包裹信息")
    @Parameter(name = "orderNumber", description = "订单号")
    public ServerResponseEntity<OrderParam> info(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderDetailByOrderNumberAndShopId(orderNumber, shopId);
        // 处理下赠品
        List<OrderItem> orderItemDbList = orderItemService.getOrderItemsByOrderNumber(orderNumber);
        Map<Long, List<OrderItem>> giveawayMap = orderItemDbList.stream().filter(item -> Objects.nonNull(item.getGiveawayOrderItemId()))
                .collect(Collectors.groupingBy(OrderItem::getGiveawayOrderItemId));
        for (OrderItem orderItem : order.getOrderItems()) {
            // 放入赠品
            if(giveawayMap.containsKey(orderItem.getOrderItemId())){
                orderItem.setGiveawayList(giveawayMap.get(orderItem.getOrderItemId()));
            }
        }

        if (Objects.nonNull(order.getDvyType()) && order.getDvyType().equals(DvyType.STATION.value())) {
            OrderSelfStation orderSelfStation = orderSelfStationService.getOne(new LambdaQueryWrapper<OrderSelfStation>().eq(OrderSelfStation::getOrderNumber, order.getOrderNumber()));
            order.getUserAddrOrder().setMobile(orderSelfStation.getStationUserMobile());
            order.getUserAddrOrder().setReceiver(orderSelfStation.getStationUserName());
        }
        OrderParam orderParam = BeanUtil.map(order, OrderParam.class);
        orderParam.setFreeFreightAmount(order.getFreeTransfee());
        orderParam.setScore(orderParam.getOrderItems().stream().mapToLong(OrderItem::getUseScore).sum());
        //查询包裹信息
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.getAndDeliveryItemInfo(orderNumber);
        orderParam.setDeliveryExpresses(deliveryOrders);
        return ServerResponseEntity.success(orderParam);
    }

    @GetMapping("/deliveryOrder/{orderDeliveryId}")
    @Operation(summary =  "物流包裹查询接口", description = "根据orderDeliveryId查询订单包裹信息")
    @Parameter(name = "orderDeliveryId", description = "订单物流包裹id")
    public ServerResponseEntity<DeliveryOrder> info(@PathVariable("orderDeliveryId") Long orderDeliveryId) {
        DeliveryOrder deliveryOrder = deliveryOrderService.deliveryOrderItemInfo(orderDeliveryId);
        return ServerResponseEntity.success(deliveryOrder);
    }



    /**********************        兑换订单物流地址         ****************************/

    /**
     * 兑换订单项待发货数量查询
     */
    @GetMapping("/getExchangeOrderItemUnDelivery/{orderNumber}")
    @Operation(summary =  "兑换订单项待发货数量查询")
    @Parameter(name = "orderNumber", description = "订单号")
    public ServerResponseEntity<ExchangeRightsDto> getExchangeOrderItemUnDelivery(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        ExchangeRightsDto exchangeRecordByOrderNumber = exchangeRecordService.getExchangeRecordByOrderNumber(orderNumber,shopId);
        if (Objects.isNull(exchangeRecordByOrderNumber)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(exchangeRecordByOrderNumber.getAddressId());
        exchangeRecordByOrderNumber.setUserAddrOrder(userAddrOrder);
        return ServerResponseEntity.success(exchangeRecordByOrderNumber);
    }


    @PutMapping("/exchangeOrderItemsDelivery")
    @Operation(summary =  "兑换订单项分包裹发货")
    public ServerResponseEntity<Void> exchangeOrderItemsDelivery(@RequestBody ExchangeRightsParam exchangeRightsParam) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        if(Objects.isNull(exchangeRightsParam.getOrderNumber()) || Objects.isNull(exchangeRightsParam.getDvyId()) || Objects.isNull(exchangeRightsParam.getDvyFlowId()) || Objects.isNull(exchangeRightsParam.getDvyType())){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        Delivery byId = deliveryService.getById(exchangeRightsParam.getDvyId());
        if(Objects.isNull(byId)){
            throw new YamiShopBindException("物流公司信息不存在");
        }
        ExchangeRightsDto exchangeRecordByOrderNumber = exchangeRecordService.getExchangeRecordByOrderNumber(exchangeRightsParam.getOrderNumber(),shopId);
        if (Objects.isNull(exchangeRecordByOrderNumber)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        if(StrUtil.isNotEmpty(exchangeRecordByOrderNumber.getDvyFlowId())){
            throw new YamiShopBindException("该订单已有物流信息，请联系管理员");
        }
        exchangeRightsParam.setDvyFlowId(exchangeRightsParam.getDvyFlowId());
        exchangeRightsParam.setDvyName(byId.getDvyName());
        exchangeRightsParam.setDvyId(exchangeRightsParam.getDvyId());
        exchangeRightsParam.setOrderNumber(exchangeRightsParam.getOrderNumber());
        exchangeRightsParam.setDvyType(exchangeRightsParam.getDvyType());
        exchangeRightsParam.setAddress(exchangeRecordByOrderNumber.getAddress());
        exchangeRightsParam.setCreateTime(new Date());
        exchangeRightsParam.setPhone(exchangeRecordByOrderNumber.getPhone());
        exchangeRightsParam.setProdName(exchangeRecordByOrderNumber.getProdName());
        exchangeRightsParam.setRealmName(exchangeRecordByOrderNumber.getRealmName());
        exchangeRightsParam.setShopId(shopId);
        exchangeRightsParam.setUserId(exchangeRecordByOrderNumber.getUserId());
        exchangeRightsParam.setStatus("3");
        deliveryOrderService.saveDeliveriesInfo(exchangeRightsParam, shopId);
        //修改为发货状态

        ExchangeRecord exchengeRecord = new ExchangeRecord();
        exchengeRecord.setId(exchangeRecordByOrderNumber.getId());
        exchengeRecord.setStatus("3");
        exchengeRecord.setDvyType(exchangeRightsParam.getDvyType());
        exchengeRecord.setProvince(exchangeRightsParam.getProvince());
        exchengeRecord.setCity(exchangeRightsParam.getCity());
        exchangeRecordService.updateById(exchengeRecord);
        return ServerResponseEntity.success();
    }

    @PutMapping("/getExchangeOrderDeliveries/{orderNumber}")
    @Operation(summary =  "根据订单号查询订单物流包裹信息")
    @Parameter(name = "orderNumber", description = "订单号")
    public ServerResponseEntity<List<DeliveryOrder>> getExchangeOrderDeliveries(@PathVariable("orderNumber") String orderNumber) {
        List<DeliveryOrder> deliveryOrders = deliveryOrderService.listExchangeDetailDelivery(orderNumber);
        return ServerResponseEntity.success(deliveryOrders);
    }

    @GetMapping("/deliveryExchangeOrder/{orderNumber}")
    @Operation(summary =  "物流包裹查询接口", description = "根据orderDeliveryId查询订单包裹信息")
    @Parameter(name = "orderNumber", description = "订单号")
    public ServerResponseEntity<DeliveryOrder> deliveryExchangeOrder(@PathVariable("orderNumber") String orderNumber) {
        DeliveryOrder deliveryOrder = deliveryOrderService.deliveryExchangeOrderItemInfo(orderNumber);
        return ServerResponseEntity.success(deliveryOrder);
    }

}
